package com.example.crew9.royalchef;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.LayoutInflaterCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.widget.Toast.LENGTH_SHORT;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout drawerLayout;
    private ActionBar actionBar;
    private NavigationView navigation;
    private LinearLayout header;
    private RecyclerView recycler;
    private SwipeRefreshLayout swipeRefreshLayout;
    private LinkedList<CookingListItem> cookings;
    private CookingAdapter cookingAdapter=new CookingAdapter();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setSupportActionBar((Toolbar)findViewById(R.id.mainActivity_toolbar));
        drawerLayout=(DrawerLayout)findViewById(R.id.mainActivity_drawerLayout);
        drawerLayout.setFocusable(false);
        //ActionBar部分
        actionBar=getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeAsUpIndicator(R.mipmap.ic_launcher);
        //Navigation部分
        navigation=(NavigationView)findViewById(R.id.navigationView);
        navigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
        {
            @Override
            public boolean onNavigationItemSelected(MenuItem item){
                switch(item.getItemId())
                {
                    case R.id.navigation_stirFrying:
                        renewRecyclerView("StirFrying",new RequestCookingListCallback());
                        break;
                    case R.id.navigation_frying:
                        renewRecyclerView("Frying",new RequestCookingListCallback());
                        break;
                    case R.id.navigation_steamingAndBoiling:
                        renewRecyclerView("SteamingAndBoiling",new RequestCookingListCallback());
                        break;
                    case R.id.navigation_stewing:
                        renewRecyclerView("Stewing",new RequestCookingListCallback());
                        break;
                    case R.id.navigation_coldMixing:
                        renewRecyclerView("ColdMixing",new RequestCookingListCallback());
                        break;
                    default:
                        break;
                }
                drawerLayout.closeDrawers();
                return true;
            }
        });
        header=(LinearLayout)navigation.getHeaderView(0);
        if(header==null)
        {
            finish();
        }
        header.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Toast.makeText(MainActivity.this,"headerview:to be developed",LENGTH_SHORT).show();
            }
        });
        //RecyclerLayout部分
        recycler=(RecyclerView)findViewById(R.id.activity_recyclerView);
        recycler.setLayoutManager(new GridLayoutManager(this,2));
        recycler.setAdapter(cookingAdapter);
        renewRecyclerView("StirFrying",new RequestCookingListCallback());
        //swipeRefreshLayout部分
        swipeRefreshLayout=(SwipeRefreshLayout)findViewById(R.id.mainActivity_swipeRefreshLayout);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            Thread.sleep(2000);
                        }
                        catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                recycler.getAdapter().notifyDataSetChanged();
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        });
                    }
                }).start();
            }
        });
    }
    //工具栏相关的监听器
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                DrawerLayout drawerLayout=(DrawerLayout)findViewById(R.id.mainActivity_drawerLayout);
                drawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.toolbar_item1:
                Toast.makeText(this, "item1:to be developed", LENGTH_SHORT).show();
                break;
            case R.id.toolbar_item2:
                Toast.makeText(this, "item2:to be developed", LENGTH_SHORT).show();
                break;
            case R.id.toolbar_item3:
                Toast.makeText(this, "item3:to be developed", LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return true;
    }
    public class CookingAdapter extends RecyclerView.Adapter<CookingAdapter.ViewHolder> {
        private LinkedList<CookingListItem> cookings;
        private Context context;

        class ViewHolder extends RecyclerView.ViewHolder{
            CardView cardView;
            ImageView cookingImage;
            TextView cookingName;

            public ViewHolder(View view){
                super(view);
                cardView=(CardView)view;
                cookingImage=(ImageView)view.findViewById(R.id.cookingImage);
                cookingName=(TextView)view.findViewById(R.id.cookingName);
            }
        }

        public CookingAdapter() {
            this.cookings=new LinkedList<CookingListItem>();
        }
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if(context==null){
                context=parent.getContext();
            }
            return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.recycler_item,parent,false));
        }
        @Override
        public void onBindViewHolder(final ViewHolder holder, final int position) {
            final String cookingName=cookings.get(position).getName();
            try{
                Glide.with(context).load(new URL("http://10.0.2.2:8080//test//"+cookingName+".jpg")).into(holder.cookingImage);
            }
            catch (MalformedURLException e)
            {
                e.printStackTrace();
            }
            holder.cookingName.setText(cookingName);
            holder.cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(context,RecipeActivity.class);
                    intent.putExtra("cookingName",cookingName);
                    startActivity(intent);
                }
            });
        }
        @Override
        public int getItemCount() {
            return cookings.size();
        }
        public void setCookingList(LinkedList<CookingListItem> cookings) {
            this.cookings = cookings;
        }
    }
    private class RequestCookingListCallback implements okhttp3.Callback{
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            cookings=new Gson().fromJson(response.body().string(),new TypeToken<LinkedList<CookingListItem>>(){}.getType());
            cookingAdapter.setCookingList(cookings);
            cookingAdapter.notifyDataSetChanged();
        }
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }
    }
        private void renewRecyclerView(String heatMethod,okhttp3.Callback callback){
            //http请求
        new OkHttpClient().newCall(new Request.Builder().url("http://10.0.2.2:8080//test//"+heatMethod+"CookingList.json")
                .build()).enqueue(callback);
    }
}
